[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. import type { ReactNode, JSX } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfo } from '@growi/core';
  5. import type {
  6. IDataWithMeta, IPageInfo, IPagePopulatedToShowRevision,
  7. } from '@growi/core';
  8. import {
  9. isClient, pagePathUtils, pathUtils,
  10. } from '@growi/core/dist/utils';
  11. import ExtensibleCustomError from 'extensible-custom-error';
  12. import type {
  13. GetServerSideProps, GetServerSidePropsContext,
  14. } from 'next';
  15. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  16. import dynamic from 'next/dynamic';
  17. import Head from 'next/head';
  18. import { useRouter } from 'next/router';
  19. import superjson from 'superjson';
  20. import { BasicLayout } from '~/components/Layout/BasicLayout';
  21. import { PageView } from '~/components/PageView/PageView';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. import { RegistrationMode } from '~/interfaces/registration-mode';
  26. import type { RendererConfig } from '~/interfaces/services/renderer';
  27. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  28. import type { CurrentPageYjsData } from '~/interfaces/yjs';
  29. import type { PageModel, PageDocument } from '~/server/models/page';
  30. import type { PageRedirectModel } from '~/server/models/page-redirect';
  31. import { useEditorModeClassName } from '~/services/layout/use-editor-mode-class-name';
  32. import { useHydratePageAtoms } from '~/states/hydrate/page';
  33. import { useHydrateSidebarAtoms } from '~/states/hydrate/sidebar';
  34. import {
  35. useCurrentPageData, usePageFetcher, useCurrentPageId, useCurrentPagePath,
  36. } from '~/states/page';
  37. import {
  38. useCurrentUser,
  39. useIsForbidden, useIsSharedUser,
  40. useIsEnabledStaleNotification, useIsIdenticalPath,
  41. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  42. useDefaultIndentSize, useIsIndentSizeForced,
  43. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  44. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  45. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  46. useIsAllReplyShown, useShowPageSideAuthors, useIsContainerFluid, useIsNotCreatable,
  47. useIsUploadAllFileAllowed, useIsUploadEnabled, useIsBulkExportPagesEnabled,
  48. useElasticsearchMaxBodyLengthToIndex,
  49. useIsLocalAccountRegistrationEnabled,
  50. useIsRomUserAllowedToComment,
  51. useIsPdfBulkExportEnabled,
  52. useIsAiEnabled, useLimitLearnablePageCountPerAssistant, useIsUsersHomepageDeletionEnabled,
  53. } from '~/stores-universal/context';
  54. import { useEditingMarkdown } from '~/stores/editor';
  55. import { useRedirectFrom } from '~/stores/page-redirect';
  56. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  57. import { useCurrentPageYjsData, useSWRMUTxCurrentPageYjsData } from '~/stores/yjs';
  58. import loggerFactory from '~/utils/logger';
  59. import type { NextPageWithLayout } from './_app.page';
  60. import type { CommonProps } from './utils/commons';
  61. import {
  62. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, skipSSR, addActivity,
  63. } from './utils/commons';
  64. declare global {
  65. // eslint-disable-next-line vars-on-top, no-var
  66. var globalEmitter: EventEmitter;
  67. }
  68. const GrowiContextualSubNavigationSubstance = dynamic(() => import('~/client/components/Navbar/GrowiContextualSubNavigation'), { ssr: false });
  69. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  70. const DisplaySwitcher = dynamic(() => import('~/client/components/Page/DisplaySwitcher').then(mod => mod.DisplaySwitcher), { ssr: false });
  71. const PageStatusAlert = dynamic(() => import('~/client/components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  72. const UnsavedAlertDialog = dynamic(() => import('~/client/components/UnsavedAlertDialog'), { ssr: false });
  73. const DescendantsPageListModal = dynamic(
  74. () => import('~/client/components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal),
  75. { ssr: false },
  76. );
  77. const DrawioModal = dynamic(() => import('~/client/components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  78. const HandsontableModal = dynamic(() => import('~/client/components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  79. const TemplateModal = dynamic(() => import('~/client/components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  80. const LinkEditModal = dynamic(() => import('~/client/components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  81. const TagEditModal = dynamic(() => import('~/client/components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  82. const ConflictDiffModal = dynamic(() => import('~/client/components/PageEditor/ConflictDiffModal').then(mod => mod.ConflictDiffModal), { ssr: false });
  83. const EditablePageEffects = dynamic(() => import('~/client/components/Page/EditablePageEffects').then(mod => mod.EditablePageEffects), { ssr: false });
  84. const logger = loggerFactory('growi:pages:all');
  85. const {
  86. isPermalink: _isPermalink, isCreatablePage,
  87. } = pagePathUtils;
  88. const { removeHeadingSlash } = pathUtils;
  89. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfo>;
  90. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  91. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  92. {
  93. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  94. return v?.data != null
  95. && v?.data.toObject != null
  96. && isIPageInfo(v.meta);
  97. },
  98. serialize: (v) => {
  99. return {
  100. data: superjson.stringify(v.data.toObject()),
  101. meta: superjson.stringify(v.meta),
  102. };
  103. },
  104. deserialize: (v) => {
  105. return {
  106. data: superjson.parse(v.data),
  107. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  108. };
  109. },
  110. },
  111. 'IPageToShowRevisionWithMetaTransformer',
  112. );
  113. // GrowiContextualSubNavigation for NOT shared page
  114. type GrowiContextualSubNavigationProps = {
  115. isLinkSharingDisabled: boolean,
  116. }
  117. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  118. const { isLinkSharingDisabled } = props;
  119. const [currentPage] = useCurrentPageData();
  120. return (
  121. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  122. );
  123. };
  124. type Props = CommonProps & {
  125. pageWithMeta: IPageToShowRevisionWithMeta | null,
  126. // pageUser?: any,
  127. redirectFrom?: string;
  128. // shareLinkId?: string;
  129. isLatestRevision?: boolean,
  130. isIdenticalPathPage?: boolean,
  131. isForbidden: boolean,
  132. isNotFound: boolean,
  133. isNotCreatable: boolean,
  134. // isAbleToDeleteCompletely: boolean,
  135. templateTagData?: string[],
  136. templateBodyData?: string,
  137. isLocalAccountRegistrationEnabled: boolean,
  138. isSearchServiceConfigured: boolean,
  139. isSearchServiceReachable: boolean,
  140. isSearchScopeChildrenAsDefault: boolean,
  141. elasticsearchMaxBodyLengthToIndex: number,
  142. isEnabledMarp: boolean,
  143. isRomUserAllowedToComment: boolean,
  144. sidebarConfig: ISidebarConfig,
  145. isSlackConfigured: boolean,
  146. // isMailerSetup: boolean,
  147. isAclEnabled: boolean,
  148. // hasSlackConfig: boolean,
  149. drawioUri: string | null,
  150. // highlightJsStyle: string,
  151. isAllReplyShown: boolean,
  152. showPageSideAuthors: boolean,
  153. isContainerFluid: boolean,
  154. isUploadEnabled: boolean,
  155. isUploadAllFileAllowed: boolean,
  156. isBulkExportPagesEnabled: boolean,
  157. isPdfBulkExportEnabled: boolean,
  158. isEnabledStaleNotification: boolean,
  159. isEnabledAttachTitleHeader: boolean,
  160. // isEnabledLinebreaks: boolean,
  161. // isEnabledLinebreaksInComments: boolean,
  162. adminPreferredIndentSize: number,
  163. isIndentSizeForced: boolean,
  164. disableLinkSharing: boolean,
  165. skipSSR: boolean,
  166. ssrMaxRevisionBodyLength: number,
  167. yjsData: CurrentPageYjsData,
  168. rendererConfig: RendererConfig,
  169. aiEnabled: boolean,
  170. limitLearnablePageCountPerAssistant: number,
  171. isUsersHomepageDeletionEnabled: boolean,
  172. };
  173. const Page: NextPageWithLayout<Props> = (props: Props) => {
  174. // register global EventEmitter
  175. if (isClient() && window.globalEmitter == null) {
  176. window.globalEmitter = new EventEmitter();
  177. }
  178. const router = useRouter();
  179. useCurrentUser(props.currentUser ?? null);
  180. // commons
  181. useCsrfToken(props.csrfToken);
  182. useGrowiCloudUri(props.growiCloudUri);
  183. // page
  184. useIsContainerFluid(props.isContainerFluid);
  185. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  186. useIsForbidden(props.isForbidden);
  187. useIsNotCreatable(props.isNotCreatable);
  188. useRedirectFrom(props.redirectFrom ?? null);
  189. useIsSharedUser(false); // this page cann't be routed for '/share'
  190. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  191. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  192. useIsSearchPage(false);
  193. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  194. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  195. useIsSearchServiceReachable(props.isSearchServiceReachable);
  196. useElasticsearchMaxBodyLengthToIndex(props.elasticsearchMaxBodyLengthToIndex);
  197. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  198. useIsSlackConfigured(props.isSlackConfigured);
  199. // useIsMailerSetup(props.isMailerSetup);
  200. useIsAclEnabled(props.isAclEnabled);
  201. // useHasSlackConfig(props.hasSlackConfig);
  202. useDefaultIndentSize(props.adminPreferredIndentSize);
  203. useIsIndentSizeForced(props.isIndentSizeForced);
  204. useDisableLinkSharing(props.disableLinkSharing);
  205. useRendererConfig(props.rendererConfig);
  206. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  207. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  208. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  209. useIsAllReplyShown(props.isAllReplyShown);
  210. useShowPageSideAuthors(props.showPageSideAuthors);
  211. useIsUploadAllFileAllowed(props.isUploadAllFileAllowed);
  212. useIsUploadEnabled(props.isUploadEnabled);
  213. useIsBulkExportPagesEnabled(props.isBulkExportPagesEnabled);
  214. useIsPdfBulkExportEnabled(props.isPdfBulkExportEnabled);
  215. useIsLocalAccountRegistrationEnabled(props.isLocalAccountRegistrationEnabled);
  216. useIsRomUserAllowedToComment(props.isRomUserAllowedToComment);
  217. useIsAiEnabled(props.aiEnabled);
  218. useLimitLearnablePageCountPerAssistant(props.limitLearnablePageCountPerAssistant);
  219. useIsUsersHomepageDeletionEnabled(props.isUsersHomepageDeletionEnabled);
  220. const { pageWithMeta } = props;
  221. const pageId = pageWithMeta?.data._id;
  222. const revisionId = pageWithMeta?.data.revision?._id;
  223. const revisionBody = pageWithMeta?.data.revision?.body;
  224. useCurrentPathname(props.currentPathname);
  225. // Initialize Jotai atoms with initial data
  226. useHydratePageAtoms(pageWithMeta?.data);
  227. const { fetchAndUpdatePage } = usePageFetcher();
  228. const { trigger: mutateCurrentPageYjsDataFromApi } = useSWRMUTxCurrentPageYjsData();
  229. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  230. const [currentPageId] = useCurrentPageId();
  231. const [currentPagePath] = useCurrentPagePath();
  232. const { mutate: mutateCurrentPageYjsData } = useCurrentPageYjsData();
  233. useSetupGlobalSocket();
  234. useSetupGlobalSocketForPage(pageId);
  235. // Store initial data (When revisionBody is not SSR)
  236. useEffect(() => {
  237. if (!props.skipSSR) {
  238. return;
  239. }
  240. if (currentPageId != null && revisionId != null && !props.isNotFound) {
  241. const mutatePageData = async() => {
  242. const pageData = await fetchAndUpdatePage();
  243. mutateEditingMarkdown(pageData?.revision?.body);
  244. };
  245. // If skipSSR is true, use the API to retrieve page data.
  246. // Because pageWIthMeta does not contain revision.body
  247. mutatePageData();
  248. }
  249. }, [
  250. revisionId, currentPageId, fetchAndUpdatePage,
  251. mutateCurrentPageYjsDataFromApi, mutateEditingMarkdown, props.isNotFound, props.skipSSR,
  252. ]);
  253. // Load current yjs data
  254. useEffect(() => {
  255. if (currentPageId != null && revisionId != null && !props.isNotFound) {
  256. mutateCurrentPageYjsDataFromApi();
  257. }
  258. }, [currentPageId, mutateCurrentPageYjsDataFromApi, props.isNotFound, revisionId]);
  259. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  260. useEffect(() => {
  261. const decodedURI = decodeURI(window.location.pathname);
  262. if (isClient() && decodedURI !== props.currentPathname) {
  263. const { search, hash } = window.location;
  264. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  265. }
  266. }, [props.currentPathname, router]);
  267. // initialize mutateEditingMarkdown only once per page
  268. // need to include useCurrentPathname not useCurrentPagePath
  269. useEffect(() => {
  270. if (props.currentPathname != null) {
  271. mutateEditingMarkdown(revisionBody);
  272. }
  273. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  274. useEffect(() => {
  275. mutateCurrentPageYjsData(props.yjsData);
  276. }, [mutateCurrentPageYjsData, props.yjsData]);
  277. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  278. // So preferentially take page data from useSWRxCurrentPage
  279. // const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  280. const pagePath = currentPagePath ?? props.currentPathname;
  281. const title = generateCustomTitleForPage(props, pagePath);
  282. return (
  283. <>
  284. <Head>
  285. <title>{title}</title>
  286. </Head>
  287. <div className="dynamic-layout-root justify-content-between">
  288. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  289. <PageView
  290. className="d-edit-none"
  291. pagePath={pagePath}
  292. rendererConfig={props.rendererConfig}
  293. />
  294. <EditablePageEffects />
  295. <DisplaySwitcher />
  296. <PageStatusAlert />
  297. </div>
  298. </>
  299. );
  300. };
  301. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  302. const editorModeClassName = useEditorModeClassName();
  303. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  304. };
  305. type LayoutProps = Props & {
  306. children?: ReactNode
  307. }
  308. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  309. // Hydrate sidebar atoms with server-side data
  310. useHydrateSidebarAtoms(props.sidebarConfig, props.userUISettings);
  311. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  312. };
  313. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  314. return (
  315. <>
  316. <GrowiPluginsActivator />
  317. <DrawioViewerScript drawioUri={page.props.rendererConfig.drawioUri} />
  318. <Layout {...page.props}>
  319. {page}
  320. </Layout>
  321. <UnsavedAlertDialog />
  322. <DescendantsPageListModal />
  323. <DrawioModal />
  324. <HandsontableModal />
  325. <TemplateModal />
  326. <LinkEditModal />
  327. <TagEditModal />
  328. <ConflictDiffModal />
  329. </>
  330. );
  331. };
  332. function getPageIdFromPathname(currentPathname: string): string | null {
  333. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  334. }
  335. class MultiplePagesHitsError extends ExtensibleCustomError {
  336. pagePath: string;
  337. constructor(pagePath: string) {
  338. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  339. this.pagePath = pagePath;
  340. }
  341. }
  342. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  343. const { model: mongooseModel } = await import('mongoose');
  344. const req: CrowiRequest = context.req as CrowiRequest;
  345. const { crowi } = req;
  346. const { revisionId } = req.query;
  347. const Page = crowi.model('Page') as PageModel;
  348. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  349. const { pageService, configManager } = crowi;
  350. let currentPathname = props.currentPathname;
  351. const pageId = getPageIdFromPathname(currentPathname);
  352. const isPermalink = _isPermalink(currentPathname);
  353. const { user } = req;
  354. if (!isPermalink) {
  355. // check redirects
  356. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  357. if (chains != null) {
  358. // overwrite currentPathname
  359. currentPathname = chains.end.toPath;
  360. props.currentPathname = currentPathname;
  361. // set redirectFrom
  362. props.redirectFrom = chains.start.fromPath;
  363. }
  364. // check whether the specified page path hits to multiple pages
  365. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  366. if (count > 1) {
  367. throw new MultiplePagesHitsError(currentPathname);
  368. }
  369. }
  370. const pageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  371. const { data: page, meta } = pageWithMeta ?? {};
  372. // add user to seen users
  373. if (page != null && user != null) {
  374. await page.seen(user);
  375. }
  376. props.pageWithMeta = null;
  377. // populate & check if the revision is latest
  378. if (page != null) {
  379. page.initLatestRevisionField(revisionId);
  380. props.isLatestRevision = page.isLatestRevision();
  381. const ssrMaxRevisionBodyLength = configManager.getConfig('app:ssrMaxRevisionBodyLength');
  382. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  383. const populatedPage = await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  384. props.pageWithMeta = {
  385. data: populatedPage,
  386. meta,
  387. };
  388. }
  389. }
  390. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  391. const req: CrowiRequest = context.req as CrowiRequest;
  392. const { crowi } = req;
  393. const Page = crowi.model('Page') as PageModel;
  394. const { currentPathname } = props;
  395. const pageId = getPageIdFromPathname(currentPathname);
  396. const isPermalink = _isPermalink(currentPathname);
  397. const page = props.pageWithMeta?.data;
  398. if (props.isIdenticalPathPage) {
  399. props.isNotCreatable = true;
  400. }
  401. else if (page == null) {
  402. props.isNotFound = true;
  403. props.isNotCreatable = !isCreatablePage(currentPathname);
  404. // check the page is forbidden or just does not exist.
  405. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  406. props.isForbidden = count > 0;
  407. }
  408. else {
  409. props.isNotFound = page.isEmpty;
  410. props.isNotCreatable = false;
  411. props.isForbidden = false;
  412. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  413. if (isPermalink && page.isEmpty) {
  414. props.currentPathname = page.path;
  415. }
  416. // /path/to/page ==> /62a88db47fed8b2d94f30000
  417. if (!isPermalink && !page.isEmpty) {
  418. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  419. if (!isToppage) {
  420. props.currentPathname = `/${page._id}`;
  421. }
  422. }
  423. if (!props.skipSSR) {
  424. props.yjsData = await crowi.pageService.getYjsData(page._id.toString());
  425. }
  426. }
  427. }
  428. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  429. // const req: CrowiRequest = context.req as CrowiRequest;
  430. // const { crowi } = req;
  431. // const UserModel = crowi.model('User');
  432. // if (isUserPage(props.currentPagePath)) {
  433. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  434. // if (user != null) {
  435. // props.pageUser = JSON.stringify(user.toObject());
  436. // }
  437. // }
  438. // }
  439. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  440. const req: CrowiRequest = context.req as CrowiRequest;
  441. const { crowi } = req;
  442. const {
  443. configManager, searchService, aclService, fileUploadService,
  444. slackIntegrationService, passportService,
  445. } = crowi;
  446. props.aiEnabled = configManager.getConfig('app:aiEnabled');
  447. props.limitLearnablePageCountPerAssistant = configManager.getConfig('openai:limitLearnablePageCountPerAssistant');
  448. props.isUsersHomepageDeletionEnabled = configManager.getConfig('security:user-homepage-deletion:isEnabled');
  449. props.isSearchServiceConfigured = searchService.isConfigured;
  450. props.isSearchServiceReachable = searchService.isReachable;
  451. props.isSearchScopeChildrenAsDefault = configManager.getConfig('customize:isSearchScopeChildrenAsDefault');
  452. props.elasticsearchMaxBodyLengthToIndex = configManager.getConfig('app:elasticsearchMaxBodyLengthToIndex');
  453. props.isRomUserAllowedToComment = configManager.getConfig('security:isRomUserAllowedToComment');
  454. props.isSlackConfigured = slackIntegrationService.isSlackConfigured;
  455. // props.isMailerSetup = mailService.isMailerSetup;
  456. props.isAclEnabled = aclService.isAclEnabled();
  457. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  458. props.drawioUri = configManager.getConfig('app:drawioUri');
  459. // props.highlightJsStyle = configManager.getConfig('customize:highlightJsStyle');
  460. props.isAllReplyShown = configManager.getConfig('customize:isAllReplyShown');
  461. props.showPageSideAuthors = configManager.getConfig('customize:showPageSideAuthors');
  462. props.isContainerFluid = configManager.getConfig('customize:isContainerFluid');
  463. props.isEnabledStaleNotification = configManager.getConfig('customize:isEnabledStaleNotification');
  464. props.disableLinkSharing = configManager.getConfig('security:disableLinkSharing');
  465. props.isUploadAllFileAllowed = fileUploadService.getFileUploadEnabled();
  466. props.isUploadEnabled = fileUploadService.getIsUploadable();
  467. // TODO: remove growiCloudUri condition when bulk export can be relased for GROWI.cloud (https://redmine.weseek.co.jp/issues/163220)
  468. props.isBulkExportPagesEnabled = configManager.getConfig('app:isBulkExportPagesEnabled') && configManager.getConfig('app:growiCloudUri') == null;
  469. props.isPdfBulkExportEnabled = configManager.getConfig('app:pageBulkExportPdfConverterUri') != null;
  470. props.isLocalAccountRegistrationEnabled = passportService.isLocalStrategySetup
  471. && configManager.getConfig('security:registrationMode') !== RegistrationMode.CLOSED;
  472. props.adminPreferredIndentSize = configManager.getConfig('markdown:adminPreferredIndentSize');
  473. props.isIndentSizeForced = configManager.getConfig('markdown:isIndentSizeForced');
  474. props.isEnabledAttachTitleHeader = configManager.getConfig('customize:isEnabledAttachTitleHeader');
  475. props.sidebarConfig = {
  476. isSidebarCollapsedMode: configManager.getConfig('customize:isSidebarCollapsedMode'),
  477. isSidebarClosedAtDockMode: configManager.getConfig('customize:isSidebarClosedAtDockMode'),
  478. };
  479. props.rendererConfig = {
  480. isEnabledLinebreaks: configManager.getConfig('markdown:isEnabledLinebreaks'),
  481. isEnabledLinebreaksInComments: configManager.getConfig('markdown:isEnabledLinebreaksInComments'),
  482. isEnabledMarp: configManager.getConfig('customize:isEnabledMarp'),
  483. adminPreferredIndentSize: configManager.getConfig('markdown:adminPreferredIndentSize'),
  484. isIndentSizeForced: configManager.getConfig('markdown:isIndentSizeForced'),
  485. drawioUri: configManager.getConfig('app:drawioUri'),
  486. plantumlUri: configManager.getConfig('app:plantumlUri'),
  487. // XSS Options
  488. isEnabledXssPrevention: configManager.getConfig('markdown:rehypeSanitize:isEnabledPrevention'),
  489. sanitizeType: configManager.getConfig('markdown:rehypeSanitize:option'),
  490. customTagWhitelist: configManager.getConfig('markdown:rehypeSanitize:tagNames'),
  491. customAttrWhitelist: configManager.getConfig('markdown:rehypeSanitize:attributes') != null
  492. ? JSON.parse(configManager.getConfig('markdown:rehypeSanitize:attributes'))
  493. : undefined,
  494. highlightJsStyleBorder: configManager.getConfig('customize:highlightJsStyleBorder'),
  495. };
  496. props.ssrMaxRevisionBodyLength = configManager.getConfig('app:ssrMaxRevisionBodyLength');
  497. }
  498. /**
  499. * for Server Side Translations
  500. * @param context
  501. * @param props
  502. * @param namespacesRequired
  503. */
  504. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  505. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  506. props._nextI18Next = nextI18NextConfig._nextI18Next;
  507. }
  508. const getAction = (props: Props): SupportedActionType => {
  509. if (props.isNotCreatable) {
  510. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  511. }
  512. if (props.isForbidden) {
  513. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  514. }
  515. if (props.isNotFound) {
  516. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  517. }
  518. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  519. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  520. }
  521. return SupportedAction.ACTION_PAGE_VIEW;
  522. };
  523. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  524. const req = context.req as CrowiRequest;
  525. const { user } = req;
  526. const result = await getServerSideCommonProps(context);
  527. // check for presence
  528. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  529. if (!('props' in result)) {
  530. throw new Error('invalid getSSP result');
  531. }
  532. const props: Props = result.props as Props;
  533. if (props.redirectDestination != null) {
  534. return {
  535. redirect: {
  536. permanent: false,
  537. destination: props.redirectDestination,
  538. },
  539. };
  540. }
  541. if (user != null) {
  542. props.currentUser = user.toObject();
  543. }
  544. try {
  545. await injectPageData(context, props);
  546. }
  547. catch (err) {
  548. if (err instanceof MultiplePagesHitsError) {
  549. props.isIdenticalPathPage = true;
  550. }
  551. else {
  552. throw err;
  553. }
  554. }
  555. await injectRoutingInformation(context, props);
  556. injectServerConfigurations(context, props);
  557. await injectNextI18NextConfigurations(context, props, ['translation']);
  558. addActivity(context, getAction(props));
  559. return {
  560. props,
  561. };
  562. };
  563. export default Page;